﻿using MiniExcelLibs;
using Newtonsoft.Json;
using PanhuaWin.NCModel;
using PanhuaWin.系统管理;
using PanhuaWin.通用;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PanhuaWin.仓库.生产领用
{
    public partial class Form辅材领用 : UIPage

    {
        public Form辅材领用()
        {
            InitializeComponent();
        }

        string 工厂编号1;
        string 工厂guid1;
        string 部门编号1;
        string FormGuid;
        string StockOutType;
        int 开始行;
        int 结束行;
        string 部门guid;
        string FormWorkType = "酸洗";


        private void Form辅材领用_Resize(object sender, EventArgs e)
        {

        }

        private void uiCheckBox选中行打钩_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void Form辅材领用_Load(object sender, EventArgs e)
        {
            this.uiDatePicker1.Value = DateTime.Today;
            StockOutType = "辅料出库";

            pub.ListWorkShop(pub.sys_user, this.uiComboBoxWorkShop);

            FormGuid = Guid.NewGuid().ToString();
            清理临时表mac(pub.getMac());
            //加载可用量
            
        }

        private void 清理临时表mac(string mac)
        {
            string sql;
            sql = "delete Temp_辅料出库 where mac='" + mac + "'";
            pub.ExecuteSql(pub.ConnectionString, sql, "退出界面清理辅料出库临时表");
        }

        private void uiComboBoxWorkShop_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sql;
            工厂编号1 = this.uiComboBoxWorkShop.SelectedValue.ToString();
            sql = @"SELECT   guid, WorkShopCode, WorkShopName, AuditDate, AuditStatus, AuditId, Auditor, Remark, CreateID, Creator, 
                CreateDate, ModifyID, Modifier, ModifyDate   FROM      Dic_WorkShop     where  WorkShopCode='" + 工厂编号1 + "'      ";
            System.Data.DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {

                pub.ListWareHouse(this.uiComboBox仓库编号1, tb.Rows[0]["guid"].ToString());

            }
            pub.ListWorkLineAll(this.uiComboBoxWorkShop.SelectedValue.ToString(), this.uiComboBox产线);

            this.uiDataGridView清单.DataSource = null;
            this.uiDataGridView清单.Refresh();
            清理临时表(FormGuid);
          
        }

        private void Do库位刷新1(string 仓库编号)
        {
            string sql;

            sql = @"SELECT   guid, WorkShopCode, WorkShopName, AuditDate, AuditStatus, AuditId, Auditor, Remark, CreateID, Creator, 
                CreateDate, ModifyID, Modifier, ModifyDate   FROM      Dic_WorkShop     where  WorkShopCode='" + 工厂编号1 + "'      ";
            System.Data.DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                this.uiComboBox库位编号1.DataSource = null;
                uiComboBox库位编号1.Refresh();
                pub.ListLocation(this.uiComboBox库位编号1, 工厂编号1, this.uiTextBox库位搜索1.Text, 仓库编号);
            }
        }

        private void uiTextBox库位搜索1_TextChanged(object sender, EventArgs e)
        {
            Do库位刷新1(this.uiComboBox仓库编号1.SelectedValue.ToString());
        }


        private void uiComboBox产线_SelectedIndexChanged(object sender, EventArgs e)
        {
            string workLineCode;
            if (this.uiComboBox产线.SelectedValue != null)
            {
                workLineCode = this.uiComboBox产线.SelectedValue.ToString();

            }


            //string workLineCode;
            if (this.uiComboBox产线.SelectedValue.ToString() != "")
            {
                workLineCode = this.uiComboBox产线.SelectedValue.ToString();
                Dic_WorkLine dic_workline = pub.GetWorkLineByLineCode(工厂编号1, workLineCode);
                if (dic_workline.DepartCode != null)
                {
                    Dic_Depart dic_depart = pub.GetDepartByCode(dic_workline.DepartCode, 工厂编号1);
                    if (dic_depart.DepartCode != "")
                    {
                        this.uiTextBox部门1.Text = dic_depart.DepartCode;
                        this.uiTextBox部门名称1.Text = dic_depart.DepartName;
                    }
                    else
                    {
                        this.uiTextBox部门1.Text = "";
                        this.uiTextBox部门名称1.Text = "";
                    }
                }
                else
                {
                    this.uiTextBox部门1.Text = "";
                    this.uiTextBox部门名称1.Text = "";
                }


                //pub.ListWorkType(工厂编号1, workLineCode, this.uiComboBox去向);
            }
        }

        private void uiCheckBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void uiCheckBox显示货位_CheckedChanged(object sender, EventArgs e)
        {
            if (this.uiCheckBox显示货位.Checked)
            {
                uiComboBox库位编号1.Visible = true;
                this.uiTextBox库位搜索1.Visible = true;
            }
            else
            {
                uiComboBox库位编号1.Visible = false;
                this.uiTextBox库位搜索1.Visible = false;
            }
        }

        private void uiButton查询_Click(object sender, EventArgs e)
        {
            this.uiDataGridView清单.DataSource = null;
            this.uiDataGridView清单.Refresh();
            ListData();

        }

        private void ListData()
        {
            System.Data.DataTable tb1 = GetList();
            if (tb1.Rows.Count > 0)
            {
                this.uiDataGridView清单.AutoGenerateColumns = false;
                this.uiDataGridView清单.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                this.uiDataGridView清单.DataSource = tb1;
                this.uiDataGridView清单.Refresh();
            }
            else
            {
                this.uiDataGridView清单.DataSource = null;
                this.uiDataGridView清单.Refresh();
            }
        }

        private DataTable GetList()
        {
            
            string sql;
            sql = @"SELECT   row_number() over(order by  存货编号,批号) 序号, 时间, 工厂编号, 仓库编号, 库位编号, 存货编号, 规格型号, 批号, 主数量, 辅数量, 存货名称, 计量单位 FROM      View_辅材现存量 where 1=1 ";
            sql += " and 工厂编号='" + this.uiComboBoxWorkShop.SelectedValue.ToString() + "'";
            if (this.uiTextBox存货名称1.Text != "")
            {
                sql += " and 存货名称 ='" + this.uiTextBox存货名称1.Text.Trim().Replace("--", "") + "' ";
            }
            if (this.uiTextBox规格型号1.Text != "")
            {
                sql += " and 规格型号 ='" + this.uiTextBox规格型号1.Text.Trim().Replace("--", "") + "' ";
            }
            if (this.uiComboBox仓库编号1.SelectedText != "")
            {
                sql += " and 仓库编号 ='" + this.uiComboBox仓库编号1.SelectedValue.ToString().Replace("--", "") + "' ";
            }
            if (this.uiCheckBox显示货位.Checked)
            {
                sql += " and 库位编号 ='" + this.uiComboBox库位编号1.SelectedValue.ToString().Replace("--", "") + "' ";
            }

            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            return tb;
        }
        private DataTable GetListShort()
        {
            string sql = @"SELECT  row_number() over(order by  CreateDate) 序号, 
               Originalsize 热轧规格, Address 产地,  VolumeCodeNew 热轧批号, Weight 重量, OutputSize 轧制规格, ProductSize 成品规格,NextWorkType 去向, Material 材质, StorageLocation 库位, 
                remark 备注,Approver 审批人 ,ApproverDate 审批时间 FROM Bus_PlanPickling  where 1=1   ";
            sql += " and CreateDate>='" + this.uiDatePicker1.Value.ToString("yyyy-MM-dd") + "'";


            string WorkShopCode = this.uiComboBoxWorkShop.SelectedValue.ToString();
            sql += " and WorkShopCode='" + WorkShopCode + "'";



            if (this.uiTextBox规格型号1.Text != "")
            {
                string Originalsize = this.uiTextBox规格型号1.Text.Trim().Replace("--", "");
                sql += " and Originalsize='" + Originalsize + "'";
            }




            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            return tb;
        }

        private void uiButton导出_Click(object sender, EventArgs e)
        {
            pub.ToExcel(GetListShort());
        }

        private void uiDataGridView清单_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            开始行 = e.RowIndex;
        }

        private void uiDataGridView清单_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            结束行 = e.RowIndex;
        }

        private void uiButton选中行发出_Click(object sender, EventArgs e)
        {
            开始行 = -1;
            结束行 = -1;
            bool tags = false;
            string VolumeCodeNew;
            string StorageLocation;
            string StockOutType = "原料出库";
            string sql;
            string WorkShopCode = this.uiComboBoxWorkShop.SelectedValue.ToString();
            if (this.uiDataGridView清单.Rows.Count > 0)
            {
                ///先验证是否出库了
                for (int j = 0; j < this.uiDataGridView清单.Rows.Count; j++)
                {
                    DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                    if (urow.Cells["D选中"].Value != null)
                    {
                        if ((bool)urow.Cells["D选中"].Value)
                        {
                            VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                            StorageLocation = this.uiDataGridView清单.Rows[j].Cells["D库位"].Value.ToString();  //
                            if (!pub.IsVolumeInStorageLocation(WorkShopCode, VolumeCodeNew, StorageLocation))
                            {
                                MessageBox.Show("要发料的卷【" + VolumeCodeNew + "】库位不存在!", "提示", MessageBoxButtons.OK);
                                return;
                            }
                        }
                    }
                }
                ///

                string docCode = pub.GetDocCode(StockOutType, WorkShopCode);
                if (this.uiTextBox部门1.Text == "")
                {
                    MessageBox.Show("部门未选择!", "提示", MessageBoxButtons.OK);
                    return;
                }
                string departCode = this.uiTextBox部门1.Text;
                string guid = Guid.NewGuid().ToString();
                int k = 1;
                for (int j = 0; j < this.uiDataGridView清单.Rows.Count; j++)
                {
                    DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                    if (urow.Cells["D选中"].Value != null)
                    {
                        if ((bool)urow.Cells["D选中"].Value)
                        {
                            ///先验证是否重复了
                            if (!tags)  ///没有表头时
                            {
                                //InsertBus_StockOutV
                                sql = " insert into Bus_StockOutV(guid, StockOutType, WorkShopCode, DocCode,  DepartCode, CreateID, Creator, CreateDate,IsSendToNC)";
                                sql += " values('" + guid + "','" + StockOutType + "','" + WorkShopCode + "','" + docCode + "', '" + departCode + "','" + pub.sys_user.User_Id + "','" + pub.sys_user.UserTrueName + "', getdate(),'N')";
                                if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutV") > 0)
                                {
                                    tags = true;
                                }
                            }
                            if (tags)  //塞入表身
                            {
                                VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                                sql = @" insert into Bus_StockOutVolume(guid,Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, 
                VolumeCode, VolumeCodeNew,InventoryCode, Size, Thick, Width, Material,Virtual, Weight, CID ,Address )";
                                sql += " select  '" + guid + "',newid(),'" + docCode + "',  '" + k + "','" + WorkShopCode + "', WarehouseCode,StorageLocation,";
                                sql += " VolumeCode,VolumeCodeNew,InventoryCode,Size,Thick, Width, Material,Virtual,Weight,CID,Address ";
                                sql += " from  Bus_StockInVolume where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                                if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutVolume") > 0)
                                {
                                    sql = " update Bus_PlanPickling set ApproverID='" + pub.sys_user.User_Id + "' ,Approver='" + pub.sys_user.UserTrueName + "' ,ApproverDate =getdate()  ";
                                    sql += " where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                                    pub.ExecuteSql(pub.ConnectionString, sql, "更新酸洗计划Bus_PlanPickling审批状态");
                                    k++;
                                }
                                else
                                {
                                    MessageBox.Show("批量确认不成功!", "提示", MessageBoxButtons.OK);
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("批量确认不成功!", "提示", MessageBoxButtons.OK);
                                return;
                            }
                        }
                    }

                }

                this.uiDataGridView清单.DataSource = null;
                this.uiDataGridView清单.Refresh();
                ListData();
            }
        }

        private void uiButton选中行退回_Click(object sender, EventArgs e)
        {
            开始行 = -1;
            结束行 = -1;
            bool tags = false;
            string VolumeCodeNew;
            string StorageLocation;
            string StockOutType = "原料出库";
            string sql;
            string WorkShopCode = this.uiComboBoxWorkShop.SelectedValue.ToString();
            if (this.uiDataGridView清单.Rows.Count > 0)
            {
                ///先验证是否出库了
                for (int j = 0; j < this.uiDataGridView清单.Rows.Count; j++)
                {
                    DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                    if (urow.Cells["D选中"].Value != null)
                    {
                        if ((bool)urow.Cells["D选中"].Value)
                        {
                            VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                            StorageLocation = this.uiDataGridView清单.Rows[j].Cells["D库位"].Value.ToString();  //
                            if (!pub.IsVolumeInStorageLocation(WorkShopCode, VolumeCodeNew, StorageLocation))
                            {
                                MessageBox.Show("要发料的卷【" + VolumeCodeNew + "】库位不存在!", "提示", MessageBoxButtons.OK);
                                return;
                            }
                        }
                    }
                }
                ///

                string docCode = pub.GetDocCode(StockOutType, WorkShopCode);
                if (this.uiTextBox部门1.Text == "")
                {
                    MessageBox.Show("部门未选择!", "提示", MessageBoxButtons.OK);
                    return;
                }
                string departCode = this.uiTextBox部门1.Text;
                string guid = Guid.NewGuid().ToString();
                int k = 1;
                for (int j = 0; j < this.uiDataGridView清单.Rows.Count; j++)
                {
                    DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                    if (urow.Cells["D选中"].Value != null)
                    {
                        if ((bool)urow.Cells["D选中"].Value)
                        {
                            ///先验证是否重复了
                            if (!tags)  ///没有表头时
                            {
                                //InsertBus_StockOutV
                                sql = " insert into Bus_StockOutV(guid, StockOutType, WorkShopCode, DocCode,  DepartCode, CreateID, Creator, CreateDate,IsSendToNC)";
                                sql += " values('" + guid + "','" + StockOutType + "','" + WorkShopCode + "','" + docCode + "', '" + departCode + "','" + pub.sys_user.User_Id + "','" + pub.sys_user.UserTrueName + "', getdate(),'N')";
                                if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料退回出库塞入Bus_StockOutV") > 0)
                                {
                                    tags = true;
                                }
                            }
                            if (tags)  //塞入表身
                            {
                                VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                                sql = @" insert into Bus_StockOutVolume(guid,Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, 
                VolumeCode, VolumeCodeNew,InventoryCode, Size, Thick, Width, Material,Virtual, Weight, CID ,Address )";
                                sql += " select  '" + guid + "',newid(),'" + docCode + "',  '" + k + "','" + WorkShopCode + "', WarehouseCode,StorageLocation,";
                                sql += " VolumeCode,VolumeCodeNew,InventoryCode,Size,Thick, Width, Material,Virtual,Weight,CID,Address ";
                                sql += " from  Bus_StockInVolume where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                                if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutVolume") > 0)
                                {
                                    sql = " update Bus_PlanPickling set ApproverID='" + pub.sys_user.User_Id + "' ,Approver='" + pub.sys_user.UserTrueName + "' ,ApproverDate =getdate()  ";
                                    sql += " where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                                    pub.ExecuteSql(pub.ConnectionString, sql, "更新酸洗计划Bus_PlanPickling审批状态");
                                    k++;
                                }
                                else
                                {
                                    MessageBox.Show("批量确认不成功!", "提示", MessageBoxButtons.OK);
                                    return;
                                }
                            }
                            else
                            {
                                MessageBox.Show("批量确认不成功!", "提示", MessageBoxButtons.OK);
                                return;
                            }
                        }
                    }

                }

                this.uiDataGridView清单.DataSource = null;
                this.uiDataGridView清单.Refresh();
                ListData();
            }
        }

        



        private void uiComboBox仓库编号1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.uiDataGridView清单.DataSource = null;
            this.uiDataGridView清单.Refresh();
        }

        private void uiComboBox库位编号1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.uiDataGridView清单.DataSource = null;
            this.uiDataGridView清单.Refresh();
        }


        private void uiDataGridView清单_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            开始行 = -1;
            结束行 = -1;
            bool tags = false;
            string VolumeCodeNew;
            string StorageLocation;
            string StockOutType = "原料出库";
            string sql;
            string WorkShopCode = this.uiComboBoxWorkShop.SelectedValue.ToString();
            if (this.uiDataGridView清单.Columns[e.ColumnIndex].Name == "D发料确认")
            {
                #region  D发料确认
                int j = e.RowIndex;
                if (j >= 0)
                {
                    if (this.uiDataGridView清单.Rows.Count > 0)
                    {

                        this.uiTextBox存货编号2.Text = uiDataGridView清单.Rows[j].Cells["InventoryCode"].ToString();
                        this.uiTextBox存货名称2.Text = uiDataGridView清单.Rows[j].Cells["T_GOOD_NAME"].ToString();
                        this.uiTextBox规格型号1.Text = uiDataGridView清单.Rows[j].Cells["Size"].ToString();
                        this.uiTextBox计量单位2.Text = uiDataGridView清单.Rows[j].Cells[""].ToString();
                    }
                }

                ///

                string docCode = pub.GetDocCode(StockOutType, WorkShopCode);
                //if (this.uiTextBox部门1.Text == "")
                //{
                //    MessageBox.Show("部门未选择!", "提示", MessageBoxButtons.OK);
                //    return;
                //}
                string departCode = this.uiDataGridView清单.Rows[j].Cells["D部门编号"].Value.ToString(); ;
                string guid = Guid.NewGuid().ToString();
                int k = 1;

                DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                ///先验证是否重复了
                if (!tags)  ///没有表头时
                {
                    //InsertBus_StockOutV
                    sql = " insert into Bus_StockOutV(guid, StockOutType, WorkShopCode, DocCode,  DepartCode, CreateID, Creator, CreateDate,IsSendToNC)";
                    sql += " values('" + guid + "','" + StockOutType + "','" + WorkShopCode + "','" + docCode + "', '" + departCode + "','" + pub.sys_user.User_Id + "','" + pub.sys_user.UserTrueName + "', getdate(),'N')";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutV") > 0)
                    {
                        tags = true;
                    }
                }
                if (tags)  //塞入表身
                {
                    VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                    sql = @" insert into Bus_StockOutVolume(guid,Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, 
                VolumeCode, VolumeCodeNew,InventoryCode, Size, Thick, Width, Material,Virtual, Weight, CID ,Address )";
                    sql += " select  '" + guid + "',newid(),'" + docCode + "',  '" + k + "','" + WorkShopCode + "', WarehouseCode,StorageLocation,";
                    sql += " VolumeCode,VolumeCodeNew,InventoryCode,Size,Thick, Width, Material,Virtual,Weight,CID,Address ";
                    sql += " from  Bus_StockInVolume where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutVolume") > 0)
                    {
                        sql = " update Bus_PlanPickling set ApproverID='" + pub.sys_user.User_Id + "' ,Approver='" + pub.sys_user.UserTrueName + "' ,ApproverDate =getdate()  ";
                        sql += " where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                        pub.ExecuteSql(pub.ConnectionString, sql, "更新酸洗计划Bus_PlanPickling审批状态");
                        k++;
                    }
                    else
                    {
                        MessageBox.Show("确认不成功!", "提示", MessageBoxButtons.OK);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("确认不成功!", "提示", MessageBoxButtons.OK);
                    return;
                }
                ////重新刷新
                this.uiDataGridView清单.DataSource = null;
                this.uiDataGridView清单.Refresh();
                ListData();
                #endregion
            }

            else if (this.uiDataGridView清单.Columns[e.ColumnIndex].Name == "D计划删除")
            {
                #region  D计划删除
                int j = e.RowIndex;
                if (j >= 0)
                {
                    if (this.uiDataGridView清单.Rows.Count > 0)
                    {

                        VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                        StorageLocation = this.uiDataGridView清单.Rows[j].Cells["D库位"].Value.ToString();  //
                        if (!pub.IsPurchaseVolumeBeUsed(WorkShopCode, VolumeCodeNew, StorageLocation))
                        {
                            MessageBox.Show("要发料的卷【" + VolumeCodeNew + "】库位不存在!", "提示", MessageBoxButtons.OK);
                            return;
                        }

                    }
                }

                ///

                string docCode = pub.GetDocCode(StockOutType, WorkShopCode);
                if (this.uiTextBox部门1.Text == "")
                {
                    MessageBox.Show("部门未选择!", "提示", MessageBoxButtons.OK);
                    return;
                }
                string departCode = this.uiTextBox部门1.Text;
                string guid = Guid.NewGuid().ToString();
                int k = 1;

                DataGridViewRow urow = this.uiDataGridView清单.Rows[j];
                ///先验证是否重复了
                if (!tags)  ///没有表头时
                {
                    //InsertBus_StockOutV
                    sql = " insert into Bus_StockOutV(guid, StockOutType, WorkShopCode, DocCode,  DepartCode, CreateID, Creator, CreateDate,IsSendToNC)";
                    sql += " values('" + guid + "','" + StockOutType + "','" + WorkShopCode + "','" + docCode + "', '" + departCode + "','" + pub.sys_user.User_Id + "','" + pub.sys_user.UserTrueName + "', getdate(),'N')";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutV") > 0)
                    {
                        tags = true;
                    }
                }
                if (tags)  //塞入表身
                {
                    VolumeCodeNew = this.uiDataGridView清单.Rows[j].Cells["D热轧批号"].Value.ToString();  //
                    sql = @" insert into Bus_StockOutVolume(guid,Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, 
                VolumeCode, VolumeCodeNew,InventoryCode, Size, Thick, Width, Material,Virtual, Weight, CID ,Address )";
                    sql += " select  '" + guid + "',newid(),'" + docCode + "',  '" + k + "','" + WorkShopCode + "', WarehouseCode,StorageLocation,";
                    sql += " VolumeCode,VolumeCodeNew,InventoryCode,Size,Thick, Width, Material,Virtual,Weight,CID,Address ";
                    sql += " from  Bus_StockInVolume where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                    if (pub.ExecuteSql(pub.ConnectionString, sql, "酸洗计划原料审核出库塞入Bus_StockOutVolume") > 0)
                    {
                        sql = " update Bus_PlanPickling set ApproverID='" + pub.sys_user.User_Id + "' ,Approver='" + pub.sys_user.UserTrueName + "' ,ApproverDate =getdate()  ";
                        sql += " where VolumeCodeNew='" + VolumeCodeNew + "' and workShopCode='" + WorkShopCode + "'";
                        pub.ExecuteSql(pub.ConnectionString, sql, "更新酸洗计划Bus_PlanPickling审批状态");
                        k++;
                    }
                    else
                    {
                        MessageBox.Show("确认不成功!", "提示", MessageBoxButtons.OK);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("确认不成功!", "提示", MessageBoxButtons.OK);
                    return;
                }
                ////重新刷新
                this.uiDataGridView清单.DataSource = null;
                this.uiDataGridView清单.Refresh();
                ListData();
                #endregion
            }


        }

        private void uiButton选中行计划删除_Click_1(object sender, EventArgs e)
        {

        }

        private void uiButton保存_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您要出库么?","询问",MessageBoxButtons.OKCancel)==DialogResult.OK )
                {
                
                string sql;
                sql = "select 工厂编号, 仓库编号, 库位编号, 存货编号,  批号    from (";
                sql += " SELECT    View_辅材现存量.工厂编号, View_辅材现存量.仓库编号,";
                sql +=" View_辅材现存量.库位编号, View_辅材现存量.存货编号,  View_辅材现存量.批号, View_辅材现存量.主数量 ";
                sql += " FROM  View_辅材现存量 join Temp_辅料出库 on ";
                sql +=" (View_辅材现存量.工厂编号=Temp_辅料出库.工厂编号 and ";
                sql += " View_辅材现存量.仓库编号=Temp_辅料出库.仓库编号 and ";
                sql += " View_辅材现存量.库位编号=Temp_辅料出库.库位编号 and ";
                sql += " View_辅材现存量.存货编号=Temp_辅料出库.存货编号 and ";
                sql += " View_辅材现存量.批号=Temp_辅料出库.批号 ) ";
                sql += " union all ";
                sql += " SELECT    工厂编号, 仓库编号, 库位编号, 存货编号,  批号, 主数量*(-1)  ";
                sql += " FROM      Temp_辅料出库 where guid ='"+ FormGuid  +"') t  ";
                sql += " group by 工厂编号, 仓库编号, 库位编号, 存货编号,  批号 ";
                sql += " having sum(主数量) <0 ";
                DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
                if(tb.Rows.Count>0)
                {
                    string 存货编号 = "有存货编号:";
                    for (int i = 0; i < tb.Rows.Count; i++)
                    {
                        存货编号 += tb.Rows[i]["存货编号"].ToString() + ",";
                    }
                    存货编号 += "库存数量不够，请检查";
                    MessageBox.Show(存货编号, "提示", MessageBoxButtons.OK);
                    return;
                }
                ///
                string docCode = pub.GetDocCode("辅料出库", this.uiComboBoxWorkShop.SelectedValue.ToString());

                sql = " insert into Bus_StockOutM( guid, StockOutType, WorkShopCode, WorkShopName, DocCode, DepartCode, DepartName, WorkLineCode,  ";
                sql +=" WorkLineName, CreateID, Creator, CreateDate, IsSendToNC )";
                sql += " values('" + FormGuid + "','" + StockOutType + "','" + this.uiComboBoxWorkShop.SelectedValue.ToString() + "',";
                sql += "'" + this.uiComboBoxWorkShop.SelectedText + "','" + docCode + "','" + this.uiTextBox部门1.Text + "', '" + this.uiTextBox部门名称1.Text + "',";
                sql +="'"+ this.uiComboBox产线.SelectedValue.ToString() +"','"+ this.uiComboBox产线.SelectedText.ToString() + "','" + pub.sys_user.User_Id + "',";
                sql += "'" + pub.sys_user.UserTrueName + "', getdate(),'N')";
                if (pub.ExecuteSql(pub.ConnectionString,sql,"辅料出库塞入表头")==1)
                {
                    sql = "insert into Bus_StockOutMaterial(guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, ";
                    sql +=" InventoryCode, Size, Batch, QuantityMain)";
                    sql += " select '" + FormGuid + "',newid(),'" + docCode + "',序号,工厂编号,仓库编号,库位编号,存货编号,规格型号,批号,主数量  ";
                    sql += " from Temp_辅料出库 where guid='"+ FormGuid + "' ";
                    pub.ExecuteSql(pub.ConnectionString, sql, "辅料出库塞入表体");
                }

                //发送NC
                //send原来领用ToNC(FormGuid);

                清理临时表mac(pub.getMac());
                List临时表(FormGuid);
                ListData();
                FormGuid = Guid.NewGuid().ToString();
                
                MessageBox.Show("辅料出库成功,单号"+ docCode, "提示", MessageBoxButtons.OK);
                



            }
        }

     


        private void uiDataGridView清单_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (this.uiDataGridView清单.Columns[e.ColumnIndex].Name == "D选择")
                {
                    this.uiTextBox存货编号2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D存货编号"].Value.ToString();  //
                    this.uiTextBox存货名称2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D存货名称"].Value.ToString();  //
                    this.uiTextBox规格型号2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D规格型号"].Value.ToString();  //
                    this.uiTextBox数量2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D主数量"].Value.ToString();  //
                    this.uiTextBox计量单位2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D计量单位"].Value.ToString();  //
                    this.uiTextBox仓库2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D仓库编号"].Value.ToString();  //
                    this.uiTextBox库位2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D库位编号"].Value.ToString();  //
                    this.uiTextBox批号2.Text = this.uiDataGridView清单.Rows[e.RowIndex].Cells["D批号"].Value.ToString();  //

                    if (this.uiTextBox存货名称2.Text == "锌锭")
                    {
                        this.uiTextBox数量2.Enabled = false;
                    }
                    else
                    {
                        this.uiTextBox数量2.Enabled = true;
                    }
                }
                else
                {


                    this.uiTextBox存货编号2.Text = "";  //
                    this.uiTextBox存货名称2.Text = "";  //
                    this.uiTextBox规格型号2.Text = "";  //
                    this.uiTextBox数量2.Text = "";  //
                    this.uiTextBox计量单位2.Text = "";  //
                    this.uiTextBox仓库2.Text = "";  //
                    this.uiTextBox库位2.Text = "";  //
                    this.uiTextBox批号2.Text = "";
                }


            }

        }

        private void uiButton添加_Click(object sender, EventArgs e)
        {
            string sql;
            if (uiTextBox存货编号2.Text == "")
            {
                MessageBox.Show("存货编号不能为空!", "提示", MessageBoxButtons.OK);
                return;
            }
            if (uiTextBox部门1.Text == "")
            {
                MessageBox.Show("部门编号不能为空!", "提示", MessageBoxButtons.OK);
                return;
            }
            if (pub.Todecimal(uiTextBox数量2.Text) <= 0)
            {
                MessageBox.Show("数量有问题!", "提示", MessageBoxButtons.OK);
                return;
            }

            if (是否同一个工厂(this.uiComboBoxWorkShop.SelectedValue.ToString(), FormGuid))
            {
                MessageBox.Show("这是一个不同工厂的存货，请重新分一张单子做!", "提示", MessageBoxButtons.OK);
                return;

            }
            if (是否同一个仓库(this.uiTextBox仓库2.Text, FormGuid))
            {
                MessageBox.Show("这是一个不同仓库的存货，请重新分一张单子做!", "提示", MessageBoxButtons.OK);
                return;

            }
            if (是否同一个产线(this.uiComboBox产线.SelectedValue.ToString(), FormGuid))
            {
                MessageBox.Show("这是一个不同产线的存货，请重新分一张单子做!", "提示", MessageBoxButtons.OK);
                return;

            }
            if (!数量是否够(this.uiComboBoxWorkShop.SelectedValue.ToString(), uiTextBox存货编号2.Text, this.uiTextBox仓库2.Text, this.uiTextBox库位2.Text, this.uiTextBox批号2.Text, pub.Todecimal(this.uiTextBox数量2.Text)))
            {
                MessageBox.Show("数量不够了不能添加!", "提示", MessageBoxButtons.OK);
                return;
            }
            sql = "insert into Temp_辅料出库( guid,bguid, 工厂编号, 部门编号, 产线编号, 存货编号, 存货名称, 规格型号, 批号, 主数量, 计量单位, 仓库编号, 库位编号, MAC, 时间 )";
            sql += " values('" + FormGuid + "',newid(),'" + this.uiComboBoxWorkShop.SelectedValue.ToString() + "','" + this.uiTextBox部门1.Text + "','" + this.uiComboBox产线.SelectedValue.ToString() + "',";
            sql += " '" + this.uiTextBox存货编号2.Text + "','" + this.uiTextBox存货名称2.Text + "','" + this.uiTextBox规格型号2.Text + "','" + this.uiTextBox批号2.Text + "','" + pub.Todecimal(this.uiTextBox数量2.Text) + "',";
            sql += " '" + this.uiTextBox计量单位2.Text + "','" + this.uiTextBox仓库2.Text + "','" + this.uiTextBox库位2.Text + "','" + pub.getMac() + "',getdate())    ";
            pub.ExecuteSql(pub.ConnectionString, sql, "辅料出库塞入临时表");

            List临时表(FormGuid);


        }

        private bool 数量是否够(string 工厂编号, string 存货编号, string 仓库编号, string 库位编号, string 批号, decimal 出库数量)
        {
            string sql;
            decimal 余额数量;
            decimal 临时表数量;
            sql = "SELECT   时间, 工厂编号, 仓库编号, 库位编号, 存货编号, 规格型号, 批号, 主数量, 辅数量, 存货名称, 计量单位 FROM      View_辅材现存量 ";

            sql += "  where 工厂编号='" + 工厂编号 + "' and  仓库编号='" + 仓库编号 + "' ";
            if (库位编号 != "")
            {
                sql += "  and 库位编号 ='" + 库位编号 + "'";
            }
            if (批号 != "")
            {
                sql += "                and 批号='" + 批号 + "'  ";
            }
            sql += " and 存货编号='" + 存货编号 + "' and 主数量>='" + 出库数量 + "'";
            //已经在temp表的

            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                余额数量 = pub.Todecimal(tb.Rows[0]["主数量"].ToString());

                sql = "select  isnull(sum(主数量),0) 数量 from Temp_辅料出库 where 1=1  ";
                sql += "  and 工厂编号='" + 工厂编号 + "' and  仓库编号='" + 仓库编号 + "' ";
                if (库位编号 != "")
                {
                    sql += "  and 库位编号 ='" + 库位编号 + "'";
                }
                if (批号 != "")
                {
                    sql += "                and 批号='" + 批号 + "'  ";
                }

                sql += " and 存货编号='" + 存货编号 + "'   ";
                DataTable tb2 = pub.GetDataTable(pub.ConnectionString, sql);
                if (tb2.Rows.Count > 0)
                {
                    临时表数量 = pub.Todecimal(tb2.Rows[0]["数量"].ToString());
                    if (余额数量 - 临时表数量 - 出库数量 >= 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }

            }
            else
            {
                return false;
            }
        }

        private void List临时表(string guid)
        {
            string sql;
            sql = @"SELECT    row_number() over(order by  时间)   序号,bguid,工厂编号, 产线编号, 部门编号, 存货编号, 存货名称, 规格型号, 批号, 主数量, 计量单位, 仓库编号, 库位编号,
                MAC, 时间 FROM      Temp_辅料出库";
            sql += " where guid='" + guid + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                sql = "update Temp_辅料出库 set 序号='" + (i + 1).ToString() + "' where guid='" + guid + "'and  bguid='" + tb.Rows[i]["bguid"].ToString() + "' ";
                pub.ExecuteSql(pub.ConnectionString, sql, "更新辅料临时出库表的序号");
            }
            this.uiDataGridView临时.AutoGenerateColumns = false;
            this.uiDataGridView临时.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
           this.uiDataGridView临时.DataSource = tb;
            this.uiDataGridView临时.Refresh();

        }

        private bool 是否同一个仓库(string 仓库编号, string guid)
        {
            string sql;
            sql = "select * from Temp_辅料出库 where 仓库编号 <>'" + 仓库编号 + "' and guid='" + guid + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool 是否同一个工厂(string 工厂编号, string guid)
        {
            string sql;
            sql = "select * from Temp_辅料出库 where 工厂编号 <>'" + 工厂编号 + "' and guid='" + guid + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        private bool 是否同一个产线(string 产线编号, string guid)
        {
            string sql;
            sql = "select * from Temp_辅料出库 where 产线编号 <>'" + 产线编号 + "' and guid='" + guid + "'";
            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (tb.Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void Form辅材领用_FormClosed(object sender, FormClosedEventArgs e)
        {
            清理临时表(FormGuid);
        }

        private void 清理临时表(string guid)
        {
            string sql;
            sql = "delete Temp_辅料出库 where guid='" + guid + "'";
            pub.ExecuteSql(pub.ConnectionString, sql, "退出界面清理辅料出库临时表");
        }

        private void uiDataGridView临时_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex>=0)
            {
                string bguid = this.uiDataGridView临时.Rows[e.RowIndex].Cells["Cbguid"].Value.ToString();
                string sql;
                sql = "delete Temp_辅料出库 where bguid='" + bguid + "'";
                pub.ExecuteSql(pub.ConnectionString, sql, "删除辅材领用临时表行");
                List临时表(FormGuid);
            }
        }

        private void uiButton导入_Click(object sender, EventArgs e)
        {
            try
            {
                string path;

                this.openFileDialog1.Filter = "Excel 文件(*.xlsx)|*.xlsx";
                if (this.openFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    path = this.openFileDialog1.FileName;
                    DataTable table = (DataTable)MiniExcel.QueryAsDataTable(path, useHeaderRow: true);
                    if (table.Rows.Count > 0)
                    {
                        for (int i = 0; i < table.Rows.Count; i++)
                        {
                            string Size = table.Rows[i]["规格型号"].ToString();
                            string Batch = table.Rows[i]["批号"].ToString();
                            string QuantityMain = table.Rows[i]["出库数量"].ToString();
                            string CreateDate = table.Rows[i]["领用日期"].ToString();
                            string WorkLineName = table.Rows[i]["产线名称"].ToString();
                            string WorkLineCode = "";
                            //查询产线编号
                            string sqlWorkLineCode;
                            sqlWorkLineCode = @"SELECT   guid, WorkShopCode, DepartGuid, DepartCode, WorkType, WorkLineCode, WorkLineName, AuditDate, AuditStatus, 
                                                    AuditId, Auditor, Remark, CreateID, Creator, CreateDate, ModifyID, Modifier, ModifyDate, V1, V2
                                    FROM      Dic_WorkLine   where WorkShopCode='" + pub.全局工厂编号 + "' and  WorkLineName='" + WorkLineName + "'";
                            DataTable tb = pub.GetDataTable(pub.ConnectionString, sqlWorkLineCode);
                            if (tb.Rows.Count > 0)
                            {
                                WorkLineCode = tb.Rows[0]["WorkLineCode"].ToString();
                            }
                            //查询存货编号
                            string 存货编号 = "";
                            string 存货名称 = "锌锭";
                            string 规格型号 = Size;
                            string NC存货编号 = pub.GetInventoryCode(存货名称, 规格型号);
                            
                            //先去掉
                            //if (string.IsNullOrEmpty(NC存货编号))
                            //{
                            //    MessageBox.Show("第" + (i+1).ToString() + "行【" + 存货名称 + "," + 规格型号 + "】没有NC存货编号,请确认数据!", "提示", MessageBoxButtons.OK);
                            //    return;
                            //}

                            string docCode = pub.GetDocCode("辅料出库", this.uiComboBoxWorkShop.SelectedValue.ToString());
                            string sql = "";
                            string guid = Guid.NewGuid().ToString();
                            sql = " insert into Bus_StockOutM( guid, StockOutType, WorkShopCode, WorkShopName, DocCode, DepartCode, DepartName, WorkLineCode,  ";
                            sql += " WorkLineName, CreateID, Creator, CreateDate, IsSendToNC )";
                            sql += " values('" + guid + "','" + StockOutType + "','1001',";
                            sql += "'张家港万达薄板有限公司','" + docCode + "','', '',";
                            sql += "'" + WorkLineCode + "','" + WorkLineName + "','" + pub.sys_user.User_Id + "',";
                            sql += "'" + pub.sys_user.UserTrueName + "', '"+ CreateDate + "','N')";
                            if (pub.ExecuteSql(pub.ConnectionString, sql, "辅料出库塞入表头") == 1)
                            {
                                sql = "insert into Bus_StockOutMaterial(guid, Bguid, DocCode, RowNumber, WorkShopCode, WarehouseCode, StorageLocation, ";
                                sql += " InventoryCode, Size, Batch, QuantityMain,T_GOOD_NAME)";
                                sql += " values ('" + guid + "',newid(),'" + docCode + "','" + (i + 1).ToString() + "','1001','FLK','','" + NC存货编号 + "','" + Size + "','" + Batch + "','" + QuantityMain + "','锌锭'); ";
                                pub.ExecuteSql(pub.ConnectionString, sql, "辅料出库塞入表体");
                            }
                        }
                    }
                    MessageBox.Show("导入成功，请到辅材入库审核界面查看");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导入失败了!" + ex.ToString(), "提示", MessageBoxButtons.OK);
                pub.Delete辅料入库临时数据();
                return;
            }
        }

        private void uiButton导出模板_Click(object sender, EventArgs e)
        {
            string path;
            this.saveFileDialog1.Filter = "Excel 文件(*.xlsx)|*.xlsx";
            string sql = "select Size 规格型号,Batch 批号,QuantityMain 出库数量,'' 领用日期,'' 产线名称 from Bus_StockOutMaterial where 1=2";

            DataTable tb = pub.GetDataTable(pub.ConnectionString, sql);
            if (this.saveFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                path = this.saveFileDialog1.FileName;
                if (!File.Exists(path))
                {
                    MiniExcel.SaveAs(path, tb, true, "sheet1", ExcelType.XLSX);
                }
                else
                {
                    MessageBox.Show("文件已经存在,请重试!", "提示", MessageBoxButtons.OK);
                    return;
                }

            }
        }
    }
}
